package com.shxt.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import com.shxt.model.Menu;
import com.shxt.model.User;
import com.shxt.service.MenuService;
import com.shxt.service.UserService;
import com.shxt.util.SHAencrypt;

@Controller
public class UserController {
	@Autowired
	private UserService userService;
	@Autowired
	private MenuService menuService;
	@GetMapping("/user/login")
	public String login(){
		return "/user/login";
	}
	@PostMapping("/user/login")
	public String login(HttpServletRequest request,HttpServletResponse response,Map<String,Object> map,String account,String password){
		User user = new User();
		String encryptSHA = null;
		try{
			encryptSHA = SHAencrypt.encryptSHA(password);
			user.setUser_password(encryptSHA);
		}catch(Exception e){
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		user.setUser_account(account);
		map = this.userService.login(user);
		if(map.get("user")==null){
			map.put("message",map.get("message"));
			map.put("account",account);
			return "user/login";
		}else{
			User user2 = new User();
			user2 = (User)map.get("user");
			HttpSession session = request.getSession();
			List<Menu> sonList = this.menuService.selMenubyRoleId(user2.getFk_role_id());

			Integer[] menu_father = new Integer[sonList.size()];
			int i = 0;
			for(Menu m : sonList){
				menu_father[i] = m.getMenu_father();
				i++;
			}
			List<Menu> fatherList = this.menuService.selFather(menu_father);
			session.setAttribute("sonList" , sonList);
			session.setAttribute("fatherList" , fatherList);
			session.setAttribute("session_user" , user2);
			session.setAttribute("user_id" , user2.getUser_id());
		}
		return "redirect:/jsp/index";
	}
	@GetMapping("/jsp/index")
	public String index(){
		return "/jsp/index";
	}

}
